package org.lql.algo.codecrush.week002;

/**
 * @author: liangqinglong
 * @date: 2025-07-29 16:20
 * @description: 面试题 01.05. 一次编辑 <a href="https://leetcode.cn/problems/one-away-lcci/description/">...</a>
 **/
public class OneEditAway {

	/**
	 * 字符串有三种编辑操作:插入一个英文字符、删除一个英文字符或者替换一个英文字符。 给定两个字符串，编写一个函数判定它们是否只需要一次(或者零次)编辑。
	 * <p>
	 * <p>
	 * <p>
	 * 示例 1：
	 * <p>
	 * 输入：
	 * first = "pale"
	 * second = "ple"
	 * 输出：True
	 * <p>
	 * <p>
	 * 示例 2：
	 * <p>
	 * 输入：
	 * first = "pales"
	 * second = "pal"
	 * 输出：False
	 */
	public boolean oneEditAway(String first, String second) {
		int m = first.length();
		int n = second.length();
		if (Math.abs(m - n) > 1) { // 边界检测： 长度差大于1，直接返回false
			return false;
		}
		if (m == n) { // 边界检测： 长度差为0，判断是否只有一个字符不同
			int diff = 0;
			for (int i = 0; i < m; i++) {
				if (first.charAt(i) != second.charAt(i)) {
					diff++;
				}
			}
			return diff <= 1;
		} else { // 长度差为1，判断是否只有一个字符不同
			// 确保first是较短的字符串
			if (m > n) {
				String temp = first;
				first = second;
				second = temp;
			}
			int diff = 0;
			int i = 0, j = 0;
			while (i < m && j < n) {
				if (first.charAt(i) != second.charAt(j)) {
					diff++;
				} else {
					i++;
				}
				j++;
			}
			return diff <= 1;
		}
	}

	public static void main(String[] args) {
		OneEditAway oneEditAway = new OneEditAway();
		System.out.println(oneEditAway.oneEditAway("pale", "ple"));
		System.out.println(oneEditAway.oneEditAway("pales", "pale"));
		System.out.println(oneEditAway.oneEditAway("pale", "bale"));
		System.out.println(oneEditAway.oneEditAway("pale", "bake"));
	}
}
